#coding=utf-8
import sqlite3


class DataUtil(object):
    def __init__(self):
        print "init"
        self.conn = DataUtil.get_conn()
        self.cursor = self.conn.cursor()
        self.config = {}
        self.check_table()
        self.load_config()

    @staticmethod
    def get_conn():
        conn = sqlite3.connect('/workspace/code/crystalcoin/coin.db')
        print "Opened database successfully"
        return conn

    def check_table(self):
        sql = "select * from sqlite_master where type = 'table' and name = 'crystal_config'"
        tables = self.cursor.execute(sql)
        if tables.fetchone():
            return
        else:
            createSql = '''CREATE TABLE crystal_config (
                key    CHAR(50)  PRIMARY KEY   NOT NULL,
                value  TEXT );'''
            self.cursor.execute(createSql)
            self.conn.commit()
            self.cursor.execute("INSERT INTO crystal_config (key,value) VALUES ('version', '0.0.1' )")
            self.cursor.execute("INSERT INTO crystal_config (key,value) VALUES ('port', '6666' )")
            self.cursor.execute("INSERT INTO crystal_config (key,value) VALUES ('private', '' )")
            self.cursor.execute("INSERT INTO crystal_config (key,value) VALUES ('public', '' )")
            self.conn.commit()

    def load_config(self):
        sql = "select * from crystal_config"
        result = self.cursor.execute(sql)
        for row in result:
            self.config[row[0]] = row[1]

    def update_config(self,config_key, config_value):
        if len(''.join(config_key)) == 0:
            return False
        else:
            sql = "update crystal_config set value = '" + config_value + "' where key = '" + config_key + "'"
            self.cursor.execute(sql)
            self.conn.commit()
            return True
